<?php
/*
 * @See Clu_Db_Table_Abstract
 */
class Model_Tour extends Zend_Db_Table_Abstract
{
	//only specify the table name, everything else inherits
	protected $_name = "tours";
	protected $_primary = "id";

	public function findByPrimary($id)
	{
		if (!$id)
            return null;
        else
		    return $this->fetchRow('id = ' . $this->getAdapter()->quote($id, 'INTEGER'));
	}
	
	/**
	 * Get the tour data: including all the fields in the 'tours' table
	 * Full mode will get article data & legs data as well
	 * @param: getArticle: true or false
	 */
	public function getTourData($tid, $getTourArticle, $getLegArticle)
	{
		//require_once APP_PATH."/modules/tour/Model/TLeg.php";
 		if ($tour = $this->findByPrimary($tid))
 		{
			$ret = $tour->toArray();
			
			if ($getTourArticle)
			{
				$articleModel = new article_Model_Service();
				$ret['article'] = $articleModel->findByPrimary($tour['article_id']);
			}

			$tlegModel = new Model_TLeg();
			$ret['legs'] = $tlegModel->getLegsByTourId($tid, $getLegArticle, 'array');
//			die_a($ret['legs']);
			return $ret;
 		}
 		else 
 			return null;
	}
	
	public function transformToFormArray($row)
	{
//		die_a($row);
		$keys = array('id','name','status','lang','price','price_currency','itinery',
					  'total_duration','organizer_name','organizer_website', 'organizer_contact');
		$row = (array)$row;
		$ret = clu_array_merge($keys, $row);
		//extra data that needs transformation
		$ret['description'] 	= $row['article']['article_body']; //TODO: body or filtered_body
		$ret['departure_date'] = date_to_string($row['departure_date']);
		$ret['return_date'] = date_to_string($row['return_date']);
		$ret['type'] = explode(',',$row['type']);
		$ret['category_tour'] = $row['type'];
		//$ret['category_tour'] = $row['category'];
//		die_a($ret);
		return $ret;
	}
	
	
	public function insertRaw($data ,$options)
	{ 
//		die_a($data);
		if($options['do_validate'])
    	{
    		$form = new Form_Tour();
    		if(!$form->isValid($data))
    			return false;
		}
		$keys = array('name','itinery', 'price','price_currency','description', 'departure_date',
					  'article_id','lang','total_duration', 'status','num_of_legs',
					  'organizer_name','organizer_website','organizer_contact',
		              'return_date','poster_id');
		$t = clu_array_merge($keys, $data);
		$t['departure_date'] = string_to_date($t['departure_date']);
        $t['return_date'] = string_to_date($t['return_date']);
		$t['post_time'] = time();
		$t['type'] = $data['category_tour'];
		//$t['category'] = $data['category_tour'];
		//$t['type'] = implode(',',$data['type']);
		$a = array();
		$a['poster_name'] = $data['poster_name'];
		$t['metadata'] = serialize($a);
//		die_a($t);
		return $this->insert($t);
	}
	
	public function saveRaw($tour, $data, $id, $options)
	{
	    if((!$tour) && (!$id))
	    	return false;
	    else if(!$tour)
	       	if(!$tour = $this->findByPrimary($id))
	       		return false;

	    if ($options['do_validate'])
	    {
	    	//Validate Data here
	    }
	    //update only those keys
		$keys = array('name','itinery','price','price_currency','description',
					  'lang','total_duration',
					  'organizer_name','organizer_website','organizer_contact',
		              );
		$dbData = clu_array_merge($keys, $data);
		$dbData['lang'] = $data['tour_lang'];
		$dbData['departure_date'] = string_to_date($data['departure_date']);		              
		$dbData['return_date'] = string_to_date($data['return_date']);
		$dbData['type'] = $data['category_tour'];
		//$dbData['category'] = $data['category_tour'];
		//$dbData['type'] = implode(',',$data['type']);

		$tour->setFromArray($dbData);
        return $tour->save();
	}
	
	public function search($data)
	{	
		$keys = array('name','price','itinery', 'to_price', 'price_currency','duration_start',
					  'duration_finish', 'tours_per_page','type',
					  'poster_id','poster_time','status', 'departure_date', 'return_date',
					  'article_id', 'metadata'
		              );
        $t = clu_array_merge($keys, $data);
//		die_a($t);
		$startDate = string_to_date($t['departure_date']);
		$returnDate = string_to_date($t['return_date']);
		//select SQL query
    	$db = $this->getAdapter();
		$select = $db->select();
		
		// Add a FROM clause
        $select->from( array('t' => 'tours'));
        
        if($t['name'])
        {
        	$names = $t['name'];
        	$select->where('t.itinery LIKE ?', $db->quoteinto("%$names%","STRING"));
        }
        
        if($t['price'])
        {
        	$select->where('t.price >= ?', (float)$db->quote($t['price'],"FLOAT"))
	               ->where('t.price <= ?', (float)$db->quote($t['to_price'],"FLOAT"));
        }

        if(count($t['type'])> 1)
    	{
    		$sql = "0";
            foreach($t['type'] as $c)
               $sql .= " OR " .($db->quoteinto("find_in_set(?,t.type)", $c));
            $select->where($sql);
    	}
    	else if(count($t['type']) == 1)
    		$select->where('t.type = ?', (int)$db->quote($t['type'],'INTEGER'));
        	
        if($t['departure_date'])
        {
        	$select->where('t.departure_date >= ?', (int)$db->quote($startDate,"INT"))
	               ->where('t.return_date <= ?', (int)$db->quote($returnDate,"INT"));
        }
        
        if($t['duration_start'])
        {
        	$select->where('t.total_duration >= ?', (int)$db->quote($t['duration_start'],"INT"))
	               ->where('t.total_duration <= ?', (int)$db->quote($t['duration_finish'],"INT"));
        }
           
        if($t['price_currency'])
            $select->where('t.price_currency = ?',$db->quoteinto($t['price_currency'],"STRING"));
        
        if($t['poster_id'])
            $select->where('t.poster_id = ?',(int)$db->quote($t['poster_id'],"INT"));
        
        if($t['poster_time'])
            $select->where('t.poster_time = ?',(int)$db->quote($t['poster_time'],"INT"));
            
        if($t['status'] && $t['status'] != 'all')
    		$select->where('t.status = ?', $db->quoteinto($t['status'],'STRING'));
//    	$select->order('t.price DESC');
//		die($select);				
        return $select;
	}
	
	public function deleteByPrimary($idArray, $atomic = true)
    {
        $auth = Zend_Auth::getInstance();
    	$uIdentity = $auth->getIdentity();
    	$sess = new Zend_Session_Namespace(CLU_NS);
        $aModel = new article_Model_Service();
        foreach ($idArray as $eventId)
        {
                $tmp = $this->findByPrimary($eventId)->toArray();
                $articleIds[]   = $tmp['article_id']; 
                $posterIds[]    = $tmp['poster_id'];
        }     
        $db = $this->getAdapter();
        if ($atomic)
                $db->beginTransaction(); //@NOTE: no effect with MyISAM
        if (($uIdentity->id != $db->quote($posterIds, 'INTEGER') && strpos ($sess->userPermissions, 'delete tour') === false) || 
            ($uIdentity->id == $db->quote($posterIds, 'INTEGER') && strpos ($sess->userPermissions, 'delete tour') === false))
        {
            return false;
        }
        else 
        {
            try
            {
                $aModel->deleteByPrimary($articleIds,false); //non atomic
                $sql = "DELETE FROM tours WHERE id IN (". $db->quote($idArray, 'INTEGER') .")" ;
                $db->query($sql);
                if ($atomic)
                    $db->commit();
                return true;
            }
            catch (Exception $e)
            {
                if ($atomic)
                    $db->rollBack();
                return false;
            }
        }
    }
  
	public function bulkUpdateStatus($idArray, $data)
	{
		$idList = implode (',', $idArray);
		$db = $this->getAdapter();
        $db->beginTransaction();
        try {
            $sql =  "UPDATE tours SET status = ".$db->quote($data['status'],'STRING')." WHERE id IN (".$idList.")" ;
            $db->query($sql);
            $sql1 =  "UPDATE articles a, tours t SET a.article_status = t.status WHERE a.article_id = t.article_id" ;
            $db->query($sql1);
            $db->commit();
			return true;
        }    
        catch (Exception $e)
        {
            $db->rollBack();
            return false;
        }   	
	}
	
	public function transformToViewData($arrayData)
	{
		$keys = array('id','name','status','category','lang','price','price_currency',
					  'poster_id', 'post_time', 
					  'total_duration','organizer_name','organizer_website', 'organizer_contact',
					  'article_id', 'metadata', 'itinery');
		
		$ret = array();
		foreach ($arrayData as $key => $aData)
		{
			$tmp = array();
			$tmp = clu_array_merge($keys, $aData);
			$tmp['departure_date'] = date_to_string($aData['departure_date']);
			$tmp['return_date'] = date_to_string($aData['return_date']);
			//$tmp['post_time'] = date_to_string($aData['post_time']);
			$ret[$key] = $tmp;
		}
		return $ret;
	}


	
}
?>